const {mysql} = require('../../qcloud')
const request = require('superagent');

module.exports = async (ctx) => {
  // let url = 'https://route.showapi.com/341-1?maxResult=50&page=3&showapi_appid=77211&showapi_sign=c9eb0bdd51264a77b6638f8cb15769cf'
  // const bookinfo = await getJoke(url)
  // ctx.state.data = JSON.parse(bookinfo.text).showapi_res_body.contentlist
  // let list = JSON.parse(bookinfo.text).showapi_res_body.contentlist

  // ctx.state.data = JSON.parse(bookinfo.text).showapi_res_body.allPages


  let all = 30
  for (let index = 0; index < all; index++) {
    let url = `https://route.showapi.com/341-1?maxResult=50&page=${index+1}&showapi_appid=77211&showapi_sign=c9eb0bdd51264a77b6638f8cb15769cf`
    const bookinfo = await getJoke(url)
    // ctx.state.data = JSON.parse(bookinfo.text).showapi_res_body.contentlist
    let list = JSON.parse(bookinfo.text).showapi_res_body.contentlist

    for (let index = 0; index < list.length; index++) {
      let {id, ct, type, title, text} = list[index]
      try{
        await mysql('jokes').insert({
          id, ct, type, title, text
        })
        // ctx.state.data = {
        //   title,
        //   msg:'success'
        // }
      }catch(e){
        ctx.state = {
          code:-1,
          data:{
            msg:'新增失败:'+e.sqlMessage
          }
        }
      }
    }

  }  

}

function getJoke(url) {
  return new Promise((reslove, reject) => {
    request('GET', url).then(res => {
        // const bookinfo = JSON.parse(res.data)
        const bookinfo = res
        if(bookinfo){
          reslove(bookinfo)
        }
        reject(bookinfo)
      }
    )
  })
}